package com.campusbackend.service.impl;

import com.campusbackend.entity.CarouselImage;
import com.campusbackend.mapper.CarouselImageMapper;
import com.campusbackend.service.CarouselImageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 轮播图表 服务实现类
 * </p>
 *
 * @author yezi
 * @since 2025-07-29
 */
@Slf4j
@Service
public class CarouselImageServiceImpl extends ServiceImpl<CarouselImageMapper, CarouselImage> implements CarouselImageService {

    @Autowired
    private CarouselImageMapper carouselImageMapper;

    @Override
    public List<CarouselImage> getAllCarouselImages() {
        return carouselImageMapper.getAllCarouselImages();
    }

    @Override
    public List<CarouselImage> getActiveCarouselImages() {
        return carouselImageMapper.getActiveCarouselImages();
    }

    @Override
    public CarouselImage updateCarouselImage(Integer position, String imageUrl, String imageName, Boolean isActive) {
        // 验证position范围
        if (position == null || position < 1 || position > 6) {
            throw new IllegalArgumentException("position 必须在 1-6 范围内");
        }

        // 查找现有记录
        CarouselImage carouselImage = carouselImageMapper.findByPosition(position);
        if (carouselImage == null) {
            throw new IllegalArgumentException("轮播图位置不存在");
        }

        // 更新字段
        if (imageUrl != null) {
            // 如果imageUrl是空字符串，设置为null
            carouselImage.setImageUrl(imageUrl.trim().isEmpty() ? null : imageUrl);
        }
        
        if (imageName != null && !imageName.trim().isEmpty()) {
            carouselImage.setImageName(imageName);
        }
        
        if (isActive != null) {
            carouselImage.setIsActive(isActive);
        }

        carouselImage.setUpdateTime(LocalDateTime.now());

        // 更新数据库
        boolean updated = updateById(carouselImage);
        if (!updated) {
            throw new RuntimeException("轮播图更新失败");
        }

        return carouselImage;
    }

    @Override
    public CarouselImage findByPosition(Integer position) {
        return carouselImageMapper.findByPosition(position);
    }
}
